import CLogin from '~/store/CLogin'
import CUser from '~/store/CUser'
import Timer from './Timer'

const pages = '/pages'
const pageIndex = '/index'

const getPageUrl = (options: UniApp.ReLaunchOptions | string) =>
    pages + (typeof options === 'string' ? options : options.url) + pageIndex

export default class System {
    static tr(content: string, success: boolean = true) {
        uni.showToast({ title: content, icon: success ? 'success' : 'error' })
    }
    static sr(content: string) {
        uni.showToast({ title: content, icon: 'success' })
    }
    static er(content: string) {
        uni.showToast({ title: content, icon: 'error' })
    }

    static reLunch(options: UniApp.ReLaunchOptions | string, needLogin: boolean = false) {
        if (this.checkLogin(needLogin)) return
        const _url = getPageUrl(options)
        if (typeof options === 'string') return uni.reLaunch({ url: _url })
        options.url = _url
        uni.reLaunch(options)
    }

    static navigateTo(options: UniApp.NavigateToOptions | string, needLogin: boolean = false) {
        if (this.checkLogin(needLogin, true)) return
        const _url = getPageUrl(options)
        if (typeof options === 'string') return uni.navigateTo({ url: _url })
        options.url = _url
        uni.navigateTo(options)
    }

    static redirectTo(options: UniApp.RedirectToOptions | string, needLogin: boolean = false) {
        if (this.checkLogin(needLogin)) return
        const _url = getPageUrl(options)
        if (typeof options === 'string') return uni.redirectTo({ url: _url })
        options.url = _url
        uni.redirectTo(options)
    }

    static checkLogin(needLogin: boolean, useDialog: boolean = true) {
        if (needLogin) {
            if (CUser.info.id === undefined) {
                if (useDialog) {
                    CLogin.dialog.show = false
                    Timer.once(() => {
                        CLogin.dialog.show = true
                    }, 10)
                }
                return true
            }
        }
        return false
    }
}
